package com.study.hot.jetpack.demo_words.db;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

/**
 * <pre>
 *     author : slx
 *     time   : 2020/03/30
 *     desc   : 数据库版本升级策略
 * </pre>
 */
@Database(entities = {Words.class}, version = 1, exportSchema = false)
public abstract class WordsDatabase extends RoomDatabase {

    public static synchronized WordsDatabase getInstance(Context context) {
        return Room.databaseBuilder(context, WordsDatabase.class, "word_db")
                //.fallbackToDestructiveMigration() //数据库升级策略：会全部删除再建立新表，不推荐
                //.addMigrations(migration_2_3)
                //.addMigrations(migration_3_4)
                .build();
    }

    abstract WordsDao getWordDao();

    //添加一个字段的策略:直接使用alter修改表
    private static final Migration migration_2_3 = new Migration(2, 3) {
        @Override public void migrate(@NonNull SupportSQLiteDatabase database) {
            //使用原生SQL语句修改表
            database.execSQL("ALTER TABLE Words ADD COLUMN words_goo TEXT NOT NULL default 'g'");
        }
    };

    //如果是删除字段
    //1.先创建临时表
    //2.将原表数据写入临时表
    //3.删除原表
    //4.重命名临时表为原表
    private static final Migration migration_3_4 = new Migration(3, 4) {
        @Override public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建临时表
            database.execSQL("CREATE TABLE words_temp (id INTEGER primary key not null,words_chinese TEXT not null,words_englist TEXT not null )");
            //迁移数据
            database.execSQL("INSERT into words_temp (id,words_chinese,words_englist) select id,words_chinese,words_englist from tb_words");
            //删除原表
            database.execSQL("drop table tb_words");
            //重命名临时表
            database.execSQL("alter table words_temp rename to tb_words");
        }
    };

}
